package controllers;

import models.TA014;
import models.TA015;
import models.TB005;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import play.Logger;
import play.data.binding.ParamNode;
import play.data.validation.Validation;
import play.mvc.Controller;
import utils.TemplateSplittor;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by xuyang on 2018/1/11.
 */
public class SplitTemplate extends Controller {

    public static void index(String name, String aircraft, String smi, String type, boolean showAll) {

        int limit = showAll ? -1:50;
        List<models.TA014> items = TA014.filterBy(name, aircraft, smi, type, limit);

        render(items, aircraft, smi, type);
    }

    public static void edit(Long id, String split_template_name) {
        TA014 entity = null;

        if (id != null) {
            entity = TA014.findById(id);
        } else if (split_template_name != null && !split_template_name.isEmpty()){
            entity = (TA014) TA014.find("split_template_name = ?", split_template_name).fetch().get(0);
        }
        else {
            // create new template
            render();
        }

        List parameters = null;

        try {
            String xml = entity.template.replace("&#", "&amp;#");
            Document document = DocumentHelper.parseText(xml);
            parameters = document.selectNodes("//parameters/parameter");
            Logger.info("parameters.count = " + parameters.size());
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Map reformatTemplates = new HashMap();

        try {
            for (TA015 rft: entity.reformat_templates) {
                try {
                    String xml = rft.template;
                    Document document = DocumentHelper.parseText(xml);
                    List units = document.selectNodes("//data/unit");
                    reformatTemplates.put(rft.reformat_template_name, units);
                    Logger.info("units.count = " + units.size());

                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        entity.aircrafts.sort(new Comparator<TB005>() {
            @Override
            public int compare(TB005 o1, TB005 o2) {
                return o1.aircraft_id.compareTo(o2.aircraft_id);
            }
        });

        render(entity, parameters, reformatTemplates);
    }

    public static void save(Long id) {
        if (params.get("test") != null) {
            String template = params.get("entity.template");
            String datagramText = params.get("datagramText");
            Document doc = new TemplateSplittor(template, datagramText).invoke();

            renderXml(doc.asXML());
        }

        TA014 entity = null;
        if (id != null) {
            entity = TA014.findById(id);
            if (entity == null) {
                flash.error("Entity not found id %s", id);
                notFound();
            }
        } else {
            entity = new TA014();
        }

        entity.edit(ParamNode.convert(params.all()), "entity");
        Validation.ValidationResult vr = validation.valid(entity);

        if (validation.hasErrors()) {
            flash.error("Error: %s", vr.error.message());
            error(500, vr.error.message());
        } else {
            try {
                entity.save();
                flash.success("Successfully saved!");
                edit(entity.getId(), null);
            } catch (Exception e) {
                e.printStackTrace();
                error(500, e.getMessage());
            }
        }
    }

    public static void getXml(Long id) {
        TA014 entity = TA014.findById(id);

        renderXml(entity.template);
    }

}
